package com.markhsiu.httpserver.processor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import com.markhsiu.common.ConstantUtil;
import com.markhsiu.httpserver.event.Request;
import com.markhsiu.httpserver.event.Response;
import com.markhsiu.httpserver.event.formparse.FileFormItem;

/**
 * 处理器默认实现
 * @author Mark Hsiu
 *
 */
public class DispatcherProcessor implements Processor {

	private static final int BUFFER_SIZE = 2048;
	private static final String UPLOAD = "E:\\test\\";

	public void service(Request request, Response response) throws IOException {
		String url = request.uri();
		if(url.indexOf(".html") > 0){
			forword(request, response);
		} else if(url.indexOf(".action") > 0){
			action(request, response);
		}
		
		response.send();
	}
	
	private void action(Request request, Response response) throws IOException{
		
		if(request.hasfile()){
			List<FileFormItem> files = request.files();
			File path = new File(UPLOAD);
			if(!path.exists()){
				path.mkdirs();
			}
			OutputStream   outs = null;
			try {
				for (FileFormItem fileForm : files) {
					if(fileForm.isFileField() && fileForm.getLength() > 0){
						File file = new File(UPLOAD,fileForm.getName());
						if(file.exists()){
							file.delete();
						} 
						file.createNewFile();
						outs = new FileOutputStream(file);
						outs.write(fileForm.getBody());
						System.out.println(" ......... upload file: "+fileForm.getName());
					}	
				}
			} finally {
				if(outs != null){
					outs.close();
				}
			}
			
		}
		
		response.write(response.getSuccess().getBytes());
	}
	
	private void forword(Request request, Response response) throws IOException{
		byte[] bytes = new byte[BUFFER_SIZE];
		FileInputStream fis = null;
		try {
			File file = new File(ConstantUtil.WEB_ROOT, request.uri());
			if (file.exists()) {
				fis = new FileInputStream(file);
				int ch = 0;
				while (ch != -1) {
					ch = fis.read(bytes, 0, BUFFER_SIZE);
					if (ch == -1) {
						break;
					}
					response.write(bytes, 0, ch);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
	}
	
}
